package cn.yunhe.action;

import cn.yunhe.pojo.Book;
import cn.yunhe.service.BookService;
import cn.yunhe.util.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import java.io.*;

public class InsertBookAction extends BaseAction implements ModelDriven {
    
    private File upload;
    private String uploadContentType;
    private String uploadFileName;
    private String uploadSavePath;
    
    
    private Book book;
    BookService bookService=new BookService();

    @Override
    public String execute() throws Exception {
        String fileSavePath1=getUploadSavePath()+"\\"+getUploadFileName();
        doupload(upload,fileSavePath1);

        book.setBpic(getUploadFileName());
        /*book.setBpic(fileSavePath1);*/
        boolean flag= bookService.insertBook(book);
        if (flag){
            return super.execute();
        }else {
            return ERROR;
        }
    }

    private void doupload(File file,String fileSavePath) throws IOException {
        FileInputStream fis=new FileInputStream(file);
        byte[] buffer=new byte[1024];
        int length=-1;

        FileOutputStream fos=new FileOutputStream(fileSavePath);

        length=fis.read(buffer);
        while (length!=-1){
            fos.write(buffer);
            length=fis.read(buffer);
        }

        fis.close();
        fos.close();

    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadSavePath() {
        return ServletActionContext.getServletContext().getRealPath(uploadSavePath);
    }

    public void setUploadSavePath(String uploadSavePath) {
        this.uploadSavePath = uploadSavePath;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public Book getModel() {
        if (book==null){
            book=new Book();
        }
        return book;
    }
}
